//let Promise = require('es6.js')
const app = getApp()
const root = app.globalData.url //http://localhost:8083/topnews/index
//let Promise = require('es6.js')
import { showModal} from 'asyncwx.js'

let ajaxtimes=0 //同时发送异步请求次数
let header = {
  'Accept': 'application/json',
  'content-type': 'application/x-www-form-urlencoded',
  'Authorization':null,// wx.getStorageSync("token"), //拼接header 带上token
}
const get=(url, data)=>{
  header["Authorization"]=wx.getStorageSync("token")  //拼接header 带上token
  ajaxtimes++
  wx.showLoading({
    title: '加载中',
  })  
  return new Promise((resolve, reject) => {
    wx.request({
      url: root + url,  
      data: data,   
      header: header,
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: (res)=> {       
        
        resolve(res.data.data)
      },
      fail: ()=> {
        //console.log('reqest error', msg)
       
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        })
        reject('fail')
      },
      complete:()=>{
        ajaxtimes--
       
        if (ajaxtimes===0){
          wx.hideLoading()
        }
      }
    })
  })
}

const post=(url, data)=> {
 
  //header.Authorization=Authorization
 
  header["Authorization"]=wx.getStorageSync("token")  //拼接header 带上token
  ajaxtimes++
  wx.showLoading({
    title: '加载中',
  }) 
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: root + url,
      data: data,
      header: header,
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: (res)=> { 
       
        if(res.data.code!=200){
          wx.showModal({
            title: '错误',
            content: res.data.message,
            showCancel: false
          })
        }  
        resolve(res.data.data)
      },
      fail:  ()=> {       
        //console.log('reqest error', msg)        
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        })
        reject('fail')
      },
      complete:()=>{
        ajaxtimes--
        if (ajaxtimes===0){
          wx.hideLoading()
        }
      }
    })
  })
}
module.exports = {
  get: get,
  post: post,
  header: header,
}